import React, { useEffect, useState } from 'react'
import { Form, Input, Button, NavBar, Toast, Dialog } from 'antd-mobile'
import styles from './index.module.less'
import { uploadAvatar, updateMemberInfo } from '@/utils/my/updateuserinfo'
import { useNavigate } from 'react-router-dom'
import Loading from '@/comopnents/loading'

interface user {
  icon?: string
  nickname?: string
  username?: string
  phone?: string
}

interface img {
  current: any
}

export default function Updateuserinfo() {

  const navigate = useNavigate()

  const localInfo = JSON.parse(localStorage.getItem('userInfo') as string)

  // 用户信息
  const [userinfo] = useState(localInfo)
  // 切换修改用户信息界面
  const [showUserInfo, setShowUserInfo] = useState(true)

  // 修改后的图片地址
  const [fileUrl, setFileUrl] = useState<string>()
  // 是否点击了更新
  const [isLoading, setIsLoading] = useState<boolean>(false)


  const initialFormVal = {
    icon: userinfo.icon,
    id: userinfo.id,
    username: userinfo.username,
    nickname: userinfo.nickname,
    phone: userinfo.phone,
  }

  // 上传图片
  const updateImg = (e?: any) => {
    const files = e.target.files
    // 判断是否有文件
    if (!files.length) return
    // 上传文件 
    let formData = new FormData()
    formData.append('file', files[0], files[0].name)
    upLoadImg(formData)
  }

  // 上传头像的请求
  const upLoadImg = async (data: any) => {
    let res: resType = await uploadAvatar(data)
    if (res.code === 20000) {
      console.log(res.data.fileUrl)
      setFileUrl(res.data.fileUrl)
      return
    }
  }


  // 返回上一页
  const back = () => {
    window.history.back()
  }


  // 点击修改用户信息
  const changeUserInfo = () => {
    setShowUserInfo(false)
  }

  // 退出登录
  const exitBtn = () => {
    Dialog.confirm({
      title: '退出提示',
      content: '您确定要退出登录吗？',
      onConfirm: () => {
        localStorage.clear()
        navigate('/my/login')
      },
      onCancel: () => {
        Toast.show({
          content: '你取消了退出',
          duration: 1000
        })
      }
    })
  }

  // 更新用户信息
  const onFinish = (info: user) => {
    info.icon = fileUrl ? fileUrl : userinfo.icon
    updateInfo(info)
    setIsLoading(true)
  }

  // 更新用户信息的请求
  const updateInfo = async (info?: object) => {
    let res: resType = await updateMemberInfo(info);
    if (res.code === 20000) {
      Toast.show({
        icon: 'success',
        content: '即将进入登录页面重新登录',
        duration: 1000,
        afterClose: () => {
          localStorage.clear()
          navigate('/my/login')
          setIsLoading(false)
        }
      })
      return
    }
    setIsLoading(false)
  }

  return (
    <div>
      <div className={styles.navBar}>
        <NavBar onBack={back}>乐居</NavBar>
      </div>

      <div className={styles.changeBox}>
        {
          showUserInfo ?
            <Button color='primary' fill='outline' onClick={changeUserInfo}>
              修改用户信息
            </Button> : null
        }
      </div>

      <Form layout='horizontal' mode='card' className={styles.formBox} onFinish={onFinish} initialValues={initialFormVal} requiredMarkStyle='text-required'>
        <Form.Item label='头像' name='icon'>
          <div className={styles.imgBox}>
            <img className={styles.tx} src={fileUrl ? fileUrl : userinfo.icon} alt="logo" />
            {
              showUserInfo ?
                null :
                <input type="file" className={styles.ImgInput} name="file" onChange={updateImg} />
            }

          </div>
        </Form.Item>
        <Form.Item label='用户名' name='username'>
          <Input style={{ '--text-align': 'right', "--color": "#a1a1a1" }} readOnly />
        </Form.Item>
        <Form.Item label='昵称' name='nickname' rules={[{ required: !showUserInfo }]}>
          {
            showUserInfo ?
              <Input style={{ '--text-align': 'right', "--color": "#a1a1a1" }} readOnly /> :
              <Input style={{ '--text-align': 'right' }} />
          }
        </Form.Item>
        <Form.Item label='手机号' name='phone' className={styles.bomForm} rules={[{ required: !showUserInfo, message: '请输入用户名/手机号' }, { pattern: /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/, message: '请输入正确的手机号' }]} >
          {
            showUserInfo ?
              <Input style={{ '--text-align': 'right', "--color": "#a1a1a1" }} readOnly /> :
              <Input type='number' style={{ '--text-align': 'right' }} />
          }
        </Form.Item>



        <div className={styles.bottomBtn}>
          <div style={{ width: "50%" }}>
            <Form.Item name='id'>
              {
                showUserInfo ?
                  <Button block size='middle' color='primary' onClick={exitBtn}>退出登录</Button> :
                  <Button block size='middle' type='submit' color='primary' >
                    <div className={styles.loading}>
                      {
                        isLoading ? <Loading></Loading> : <>更新</>
                      }
                    </div>
                  </Button>
              }
            </Form.Item>

          </div>
        </div>
      </Form>
    </div>
  )
}
